package com.shd.edanpei.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.shd.edanpei.R;
import com.shd.edanpei.base.BaseActivity;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.CustomerBean;
import com.shd.edanpei.bean.IdentityBean;
import com.shd.edanpei.bean.UserBean;
import com.shd.edanpei.bean.UserModel;
import com.shd.edanpei.presenter.contract.CertificationContract;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.image.LoadImageCtrl;
import com.shd.edanpei.presenter.CertificationPresenter;
import com.shd.edanpei.util.ToastUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/6/11.
 * 实名认证
 */

public class CertificationActivity extends BaseActivity<CertificationPresenter> implements CertificationContract.CertificationIView {

    public static final int FRONT_IDCARD = 1;
    public static final int BACK_IDCARD = 2;

    public static final int FROM_LOGIN = 10;
    public static final int FORM_DATA = 11;
    public static final int FROM_CREATE = 12;

    @BindView(R.id.headline)
    TextView headline;
    @BindView(R.id.iv_headline_back)
    ImageView ivBack;

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_idNumber)
    TextView tvIdNumber;
    @BindView(R.id.iv_identity_pic1)
    ImageView ivPic1;
    @BindView(R.id.iv_identity_pic2)
    ImageView ivPic2;


    private int mFrom;
    private Bundle bundle;
    private CustomerBean customerBean;


    @Override
    protected int setLayout() {
        return R.layout.activity_certification;
    }

    @Override
    protected CertificationPresenter bindPresenter() {
        return new CertificationPresenter(this);
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        loadImageCtrl = new LoadImageCtrl(this);
        headline.setText(R.string.certification);
        bundle = getIntent().getExtras();
        mFrom = bundle.getInt(Constant.FROM);

        if (mFrom == FORM_DATA) {
            checkIsIdentity();
        } else if (mFrom == FROM_CREATE) {
            headline.setText("客户实名认证");
            customerBean = bundle.getParcelable(Constant.DATA);
        }
        toCustomerInfoActivity();
    }

    private void checkIsIdentity() {
        UserBean userEntity = DaoManager.getInstance().getUserBean();
        if (userEntity.isReal()) {
            showLoading("");
            //回显数据
            ivPic1.setClickable(false);
            ivPic2.setClickable(false);
            hideView(R.id.tv_identity_pic1, R.id.tv_identity_pic2, R.id.tv_submit, R.id.tv_hint);

            tvName.setText(userEntity.getRealName());
            tvIdNumber.setText(userEntity.getIdNumber());

            ApiCreator.getApi().getUser(DaoManager.getInstance().getUserBean().getId())
                    .compose(RxTransformer.<UserModel>errorHandle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<UserModel>() {
                        @Override
                        protected void onSuccess(UserModel data) {
                            List<String> idCardPic = data.getIdCardPic();
                            loadImageCtrl.getGlide().load(idCardPic.get(0)).into(ivPic1);
                            ivPic1.setBackground(null);
                            ivPic2.setBackground(null);
                            loadImageCtrl.getGlide().load(idCardPic.get(1)).into(ivPic2);
                            tvName.setText(data.getRealName());
                            tvIdNumber.setText(data.getIdNumber());
                        }

                        @Override
                        public void onFinish() {
                            stopLoading();
                        }
                    });

        }
    }

    @Override
    protected void initListener() {

    }

    @OnClick(R.id.iv_identity_pic1)
    void clickPic1() {
        ChoosePicActivity.start(this, FRONT_IDCARD);
    }

    @OnClick(R.id.iv_identity_pic2)
    void clickPic2() {
        ChoosePicActivity.start(this, BACK_IDCARD);
    }

    @OnClick(R.id.tv_submit)
    void submit() {
        if (mFrom == FROM_CREATE) {
            if (name != null) {
                bundle.putInt(Constant.FROM, CustomerInfoActivity.NEW_INFO);
                customerBean.setName(name);
                customerBean.setIdCardNo(idNumber);
                customerBean.setBirthday(birthday);
                customerBean.setSex(gender + "");
                bundle.putParcelable(Constant.DATA, customerBean);
                mPresenter.toCustomer(bundle);
                //保存数据
                DaoManager.getInstance().setIdCardRealName(name);
                DaoManager.getInstance().setIdBirthday(birthday);
                DaoManager.getInstance().setIdSex(gender);
                DaoManager.getInstance().setIdnumber(idNumber);
            } else {
                ToastUtil.showToast("请先实名认证");
            }

        } else {
            mPresenter.submit(tvName.getText().toString(), tvIdNumber.getText().toString(), mFrom);
        }
    }

    @OnClick(R.id.iv_headline_back)
    void close() {
        if (mFrom == FROM_LOGIN) {
            startActivity(LoginActivity.class);
            DaoManager.getInstance().logout();
            finish();
        } else if (mFrom == FORM_DATA) {
            finish();
        } else if (mFrom == FROM_CREATE) {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close();
        }


        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //编辑返回
        if (null != data) {
            switch (resultCode) {
                case FRONT_IDCARD:
                    String picPath1 = data.getStringExtra(ChoosePicActivity.INTENT_BACK_DATA);
                    showView(R.id.pb_identity_pic1);
                    hideView(R.id.tv_identity_pic1);
                    mPresenter.uploadCertificationPic(picPath1, FRONT_IDCARD);
                    break;
                case BACK_IDCARD:
                    String picPath2 = data.getStringExtra(ChoosePicActivity.INTENT_BACK_DATA);
                    showView(R.id.pb_identity_pic2);
                    hideView(R.id.tv_identity_pic2);
                    mPresenter.uploadPic(picPath2, BACK_IDCARD);
                    break;
            }
        }
    }

    @Override
    public void setPic(String picUrl, int pic) {
        switch (pic) {
            case FRONT_IDCARD:
                loadImageCtrl.getGlide().load(picUrl).into(ivPic1);
                hideView(R.id.pb_identity_pic1);
              //  showView(R.id.tv_identity_pic1);
                break;
            case BACK_IDCARD:
                loadImageCtrl.getGlide().load(picUrl).into(ivPic2);
                hideView(R.id.pb_identity_pic2);
               // showView(R.id.tv_identity_pic2);
                break;
        }
    }

    private String name;
    private String idNumber;
    private String birthday;
    private int gender;

    @Override
    public void setIdentitiyInfo(IdentityBean data) {
        name = data.getName();
        gender = data.getSex();
        idNumber = data.getIdCard();
        birthday = data.getBirthday();
        loadImageCtrl.getGlide().load(data.getUrl()).into(ivPic1);
        hideView(R.id.pb_identity_pic1);
       // showView(R.id.tv_identity_pic1);
        tvName.setText(data.getName());
        tvIdNumber.setText(data.getIdCard());
    }

    @Override
    public void updateFail(int pic) {
        switch (pic) {
            case FRONT_IDCARD:
                hideView(R.id.pb_identity_pic1);
              //  showView(R.id.tv_identity_pic1);
                break;
            case BACK_IDCARD:
                hideView(R.id.pb_identity_pic2);
              //  showView(R.id.tv_identity_pic2);
                break;
        }
    }

    public void toCustomerInfoActivity() {
        UserBean userBean=DaoManager.getInstance().getUserBean();
        if (null!=userBean.getIdCardName()) {

           // mPresenter.isReal();

            bundle.putInt(Constant.FROM, CustomerInfoActivity.NEW_INFO);
            customerBean.setName(userBean.getIdCardName());
            customerBean.setIdCardNo(userBean.getIdCardNumber());
            customerBean.setBirthday(userBean.getIdCardBirthday());
            customerBean.setSex(userBean.getIdCardSex2());
            bundle.putParcelable(Constant.DATA, customerBean);
            mPresenter.toCustomer(bundle);
        }
    }


    /**
     * 显示view
     */
    private void showView(@IdRes int... ids) {
        for (int id : ids) {
            findViewById(id).setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏view
     */
    private void hideView(@IdRes int... ids) {
        for (int id : ids) {
            findViewById(id).setVisibility(View.GONE);
        }
    }
}
